from rest_framework import serializers

from sqtp.models import User, Environment, Case
from sqtp.models.task import Plan, Report
from sqtp.serializers import UserSerializer, EnvironmentSerializer, CaseSerializer


class PlanSerializer(serializers.ModelSerializer):
    status = serializers.SerializerMethodField()
    executor_id = serializers.PrimaryKeyRelatedField(
        queryset=User.objects.all(), source='executor'
    )
    executor = UserSerializer(read_only=True)
    environment_id = serializers.PrimaryKeyRelatedField(
        queryset=Environment.objects.all(), source='environment'
    )
    environment = EnvironmentSerializer(read_only=True)
    case_ids = serializers.PrimaryKeyRelatedField(queryset=Case.objects.all(), many=True, required=False,
                                                  write_only=True, source='cases')  # 自动配model里的
    cases = CaseSerializer(read_only=True, many=True)  # 是序列化读取时用的，展示完整的关联对象信息
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H', read_only=True)
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H', read_only=True)
    create_by = UserSerializer(write_only=True, required=False)
    update_by = UserSerializer(write_only=True, required=False)

    class Meta:
        model = Plan
        # 写all的话同名字段会被覆盖
        fields = '__all__'

    def get_status(self, obj):
        return obj.get_status_display()

    # 这个是补充不会覆盖滴,也是系统验证后再执行的，
    # env_id = attrs.get('environment_id', 0),上面source='executor'，所以呀不会有_id这些了
    # executor_id = attrs.get('executor_id', 0)
    # def validate(self, attrs):
    #     env_id = attrs.get('environment_id', 0)
    #     executor_id = attrs.get('executor_id', 0)
    #     if not Environment.objects.filter(pk=env_id).exists():
    #         raise serializers.ValidationError(f"请输入正确的env_id:{env_id}")
    #     if not User.objects.filter(pk=executor_id).exists():
    #         raise serializers.ValidationError(f"请输入正确的executor:{executor_id}")
    #     return attrs


class ReportSerializer(serializers.ModelSerializer):
    plan = PlanSerializer(read_only=True)
    trigger = UserSerializer(read_only=True)
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)  # 开始时间
    update_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S', read_only=True)  # 结束时间

    class Meta:
        model = Report
        fields = '__all__'
